<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="editMode ? '编辑需求' : '新建需求'"
    width="700px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      class="dialog-form"
    >
      <el-descriptions :column="1" border class="custom-descriptions">
        <el-descriptions-item label="*需求名称">
          <el-form-item prop="deName" style="margin-top: 11px;">
            <el-input
              v-model="form.deName"
              placeholder="请输入"
              :maxlength="100"
              show-word-limit
              style="width: 100%;"
            />
          </el-form-item>
        </el-descriptions-item>
        
        <el-descriptions-item label="*需求类别">
          <el-form-item prop="deType" style="margin-top: 11px;">
            <el-radio-group v-model="form.deType">
              <el-radio v-for="item in requirementTypeOptions" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-descriptions-item>
        
        <el-descriptions-item label="*物料内容">
          <el-form-item prop="maId" style="margin-top: 11px;">
            <el-tree-select
              v-model="form.maId"
              :data="materialTreeData"
              placeholder="请选择"
              :props="treeSelectProps" 
              filterable
              allow-clear
              :disabled="false"
              style="width: 100%;"
              @change="handleMaterialChange"
            />
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessageBox } from 'element-plus'
import { ElTreeSelect } from 'element-plus'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  editMode: {
    type: Boolean,
    required: true,
    default: false
  },
  requirementTypeOptions: {
    type: Array,
    required: true
  },
  materialTreeData: {
    type: Array,
    required: true
  },
  initialFormData: {
    type: Object,
    default: () => ({})
  }
})

// 定义emits
const emit = defineEmits(['close', 'submit', 'update:visible'])

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  deName: '',
  deType: 1,
  maId: '',
})

// 存储之前选择的物料ID，用于取消切换时恢复
let previousMaId = ''

// 树形选择配置
const treeSelectProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}

// 表单校验规则
const rules = {
  deName: [
    { required: true, message: '请输入需求名称', trigger: 'blur' },
    { min: 1, max: 100, message: '需求名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  deType: [
    { required: true, message: '请选择需求类别', trigger: 'change' }
  ],
  maId: [
    { required: true, message: '请选择物料内容', trigger: 'change' }
  ]
}

// 监听初始数据变化
// watch(
//   () => props.initialFormData,
//   (newVal) => {
//     if (newVal) {
//       console.log('编辑、新增弹窗数据', newVal)
//       Object.assign(form, {
//         deName: newVal.dname || '',
//         deType: newVal.dtype || 1,
//         maId: newVal.maId || newVal.mid || '', // 尝试使用maId，如果不存在则使用mid
//       })
//     }
//   },
//   { immediate: true }
// )

// 监听visible变化，确保弹窗打开时能正确显示数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.editMode && props.initialFormData) {
      // console.log('弹窗打开，更新表单数据:', props.initialFormData)
      Object.assign(form, {
        deName: props.initialFormData.dname || '',
        deType: props.initialFormData.dtype || 1,
        maId: props.initialFormData.maId || props.initialFormData.mid || '',
      })
      // 编辑模式下记录初始物料ID
      previousMaId = form.maId
    }
  }
)

// 处理物料内容切换
const handleMaterialChange = (newMaId) => {
  // 只在编辑模式下进行确认提示
  if (props.editMode && previousMaId && newMaId && newMaId !== previousMaId) {
    ElMessageBox.confirm('确认切换物料？切换后已填写内容一并删除', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 用户确认切换，更新之前的物料ID
      previousMaId = newMaId
    }).catch(() => {
      // 用户取消切换，恢复之前的物料ID
      form.maId = previousMaId
    })
  } else {
    // 新增模式下或物料ID未变化，直接更新
    previousMaId = newMaId
  }
}

// 处理关闭
const handleClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 手动重置默认值
  form.deType = 1
  emit('update:visible', false)
}

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    emit('submit', { ...form })
    emit('update:visible', false)
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 判断是否为第三级节点
const isThirdLevelNode = (node) => {
  // 根据实际数据结构调整判断逻辑
  return node.level === 3
}
</script>

<style scoped>
/* 从index.vue迁移相关样式 */
.custom-descriptions {
  width: 100%;
}

.custom-descriptions .el-descriptions__item {
  display: flex;
  border-bottom: 1px solid #EBEEF5;
}

.custom-descriptions .el-descriptions__label {
  width: 120px;
  font-weight: 500;
  color: #606266;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.custom-descriptions .el-descriptions__content {
  flex: 1;
  color: #303133;
  display: flex;
  align-items: center;
  padding: 18px 10px 0 10px !important;
}

.custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
  border-bottom: none;
}

.el-descriptions__cell--label {
  background-color: transparent !important;
}
:deep(.custom-descriptions .el-descriptions__cell) {
  padding: 0px 11px !important;
}
.el-form-item {
  margin-bottom: 11px;
}
</style>